package javascriptInJava;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;

/**
 * java中使用javascript
 */
public class Main {
    public static void main(String[] args) throws FileNotFoundException, ScriptException, NoSuchMethodException {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");
        engine.eval(new InputStreamReader(new FileInputStream(new File("E:\\dev\\practice\\out\\production\\practice\\javascriptInJava\\test.js"))));
        //3.将引擎转换为Invocable，这样才可以掉用js的方法
        Invocable invocable = (Invocable) engine;
        //4.使用 invocable.invokeFunction掉用js脚本里的方法，第一個参数为方法名，后面的参数为被调用的js方法的入参
        String scriptResult = (String) invocable.invokeFunction("getString", "heheda");
        System.out.println(scriptResult);
    }
}
